package com.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: cxt
 * @time: 2021/11/5
 * <p>
 * spring Bean获取
 */
@Component
@Slf4j
public class SpringJobBeanFactory implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @SuppressWarnings("unchecked") // 忽略警告
    public static <T> T getBean(String name) throws BeansException {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(name);
    }

    // 根据class的名字从spring容器中获取javabean
    public static <T> T getBeanByName(Class<T> targetClass) {
        return applicationContext.getBean(targetClass);
    }

    /**
     * 获取某一类的所有bean
     *
     * @param type
     * @return 如果异常或找不到则返回null
     */
    public static <T> Map<String, T> getBeansByType(Class<T> type) {
        try {
            return applicationContext.getBeansOfType(type);
        } catch (Exception e) {
            log.error("获取SpringBeansMap(Class:" + type.getName() + ")失败", e);
            return null;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringJobBeanFactory.applicationContext = applicationContext;
    }
}
